#!/usr/bin/python2.6
"""Test for handler.py"""

import unittest
import urllib2

import handler


PRODUCT_KEY = 'agtkdW1wY2F0Y2hlcnINCxIHUHJvZHVjdBgCDA'
SECRET = '4ceafc4082e345ec98972c00f035609b'
CLIENT = 'unittest'

EXPECTED_HMAC_DIGEST = '9d98bc4bf11cc77c22319607ad90f5beeab1938a'
SHORT_STRING = 'SomeCrashMannnnn: New Line with = sign'
LONG_STRING = 'Long string goes here.\nNew Line with = sign'


class DumpcatcherTestCase(unittest.TestCase):

  def setUp(self):
    self.dump_catcher = handler.Dumpcatcher(PRODUCT_KEY, SECRET,
                                            'http://localhost:8080/add', CLIENT)

  def test_send_crash(self):
    result = self.dump_catcher.send_crash(
        ('short', SHORT_STRING),
        ('long', LONG_STRING)
    )
    self.assertEqual(200, result.code)

  def test_many_send_crash(self):
    for i in range(50):
      self.test_send_crash()

  def test_send_crash_credentials_invalid(self):
    dc = handler.Dumpcatcher(PRODUCT_KEY, 'No', 'http://localhost:8080/add',
                             CLIENT)
    try:
      result = dc.send_crash(
          ('short', SHORT_STRING),
          ('long', LONG_STRING)
      )
    except urllib2.HTTPError, e:
      code = e.code
    self.assertEqual(401, code)

  def test_add_extra_query_pairs_and_sign(self):
    parameters = self.dump_catcher._add_extra_query_pairs_and_sign((
        ('long', LONG_STRING),
        ('short', SHORT_STRING)
    ))
    for parameter in parameters:
      if parameter[0] == 'hmac':
        found_hmac = parameter[1]
      elif parameter[0] == 'product_key':
        found_product_key= parameter[1]
      if parameter[0] == 'client':
        found_client = parameter[1]
    self.assertEqual(PRODUCT_KEY, found_product_key)
    self.assertEqual(EXPECTED_HMAC_DIGEST, found_hmac)
    self.assertEqual(CLIENT, found_client)

  def test_calculate_hmac(self):
    digest = self.dump_catcher._calculate_hmac((
        ('client', CLIENT),
        ('long', LONG_STRING),
        ('short', SHORT_STRING),
        ('product_key', PRODUCT_KEY),
    ))
    self.assertEqual(EXPECTED_HMAC_DIGEST, digest)


if __name__ == '__main__':
  unittest.main()
